#include "04_Acceptor.hpp"
//#include "05_TCPconnection.hpp"     //TCPconnection通常对外隐藏囧
#include "06_EventLoop.hpp"
#include <stdlib.h>                 // exit
#include <iostream>
#include <csignal>

namespace xy
{
// 处理ctrl + c信号，优雅退出
void signal_handler(int signum)
{
    std::cout << "Server shutdown..." << std::endl;
    exit(0);
}

// 定义回调函数
void on_connection(const TCPconnection::TCPconnectionPtr& conn)
{
    std::cout << "New connection established: " << conn->tostring() << "\n";
}

void on_message(const TCPconnection::TCPconnectionPtr& conn, const std::string &msg)
{
    std::cout << "Received message: " << msg << "\n";
}

void on_close(const TCPconnection::TCPconnectionPtr& conn)
{
    std::cout << "Connection closed: " << conn->tostring() << "\n";
}

}


int main()
{
    // 0. 注册信号处理函数（好像只有优雅退出）
    signal(SIGINT, xy::signal_handler); 

    // 1. 创建Acceptor对象，准备接受连接
    //xy::Acceptor acceptor(8080, "127.0.0.1");   // 使用端口和本地回环地址，测试阶段推荐
    xy::Acceptor acceptor(8080, "0.0.0.0");   // 使用端口和本地回环地址，测试阶段推荐
    acceptor.ready();   // 先设置复用，再调用ready(), 内部会调用bind()和listen()
    std::cout << "Server running on port 8080...\n";
    
    // 2. 开启循环
    xy::Event_Loop loop(acceptor);
    loop.set_connection_callback(xy::on_connection);
    loop.set_message_callback(xy::on_message);
    loop.set_close_callback(xy::on_close);
    loop.loop();
    

    return 0;
}

